#include "OgreStableHeaders.h"

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
#include "OgreStringConverter.h"

#include "OgreGLESPrerequisites.h"
#include "OgreGLESRenderSystem.h"

#include "OgreEGLRenderTexture.h"
#include "OgreEGLContext.h"
#include "OgreEGLSupport.h"

#include <iostream>
#include <climits>

namespace Ogre
{
	EGLPBuffer::EGLPBuffer(EGLSupport* glsupport, PixelComponentType format,
						   size_t width, size_t height)
		: GLESPBuffer(format, width, height)
	{
	}
	
	void EGLPBuffer::initEGLPBuffer()
	{
		mEglDrawable = 0;
		::EGLConfig glConfig = 0;
		
		bool isFloat = false;
		int bits = 0;
		
		switch(mFormat)
		{
			case PCT_BYTE:
				bits = 8;
				break;
				
			case PCT_SHORT:
			case PCT_FLOAT16:
				bits = 16;
				break;
				
			case PCT_FLOAT32:
				bits = 32;
				break;
				
			default:
				break;
		}
		
		if (mFormat == PCT_FLOAT16 || mFormat == PCT_FLOAT32)
		{
			OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
						"No support for Floating point PBuffers",
						"EGLRenderTexture::initEGLPBuffer");
		}
		
		EGLint minAttribs[] = {
			EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
			EGL_DEPTH_SIZE, 16,
			EGL_NONE};
			
		EGLint maxAttribs[] = {
			EGL_RED_SIZE, bits,
			EGL_GREEN_SIZE, bits,
			EGL_BLUE_SIZE, bits,
			EGL_ALPHA_SIZE, bits,
			EGL_STENCIL_SIZE, INT_MAX,
			EGL_NONE
			};
			
		EGLint pBufferAttribs[] = {
			EGL_WIDTH, mWidth,
			EGL_HEIGHT, mHeight,
			EGL_TEXTURE_TARGET, EGL_TEXTURE_2D,
			EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGB,
			EGL_NONE
			};
			
		glConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs);
		
		EGL_CHECK_ERROR;
		mEglDrawable = eglCreatePbufferSurface(mGlDisplay, glConfig, pBufferAttribs);
		EGL_CHECK_ERROR;
		
		if (!glConfig || !mEglDrawable)
		{
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
						"Unable to create Pbuffer", 
						"EGLPBuffer::EGLPBuffer");
		}
		EGLint glConfigID;
		EGLint iWidth, iHeight;
		
		eglGetConfigAttrib(mGlDisplay, glConfig, EGL_CONFIG_ID, &glConfigID);
		EGL_CHECK_ERROR;
		eglQuerySurface(mGlDisplay, mEglDrawable, EGL_WIDTH, &iWidth);
		EGL_CHECK_ERROR;
		eglQuerySurface(mGlDisplay, mEglDrawable, EGL_HEIGHT, &iHeight);
		EGL_CHECK_ERROR;
		
		mWidth = iWidth;
		mHeight = iHeight;
		LogManager::getSingleton().logMessage(LML_NORMAL, "EGLPBuffer::create used final dimensions " + StringConverter::toString(mWidth) + " x " + StringConverter::toString(mHeight));
		LogManager::getSingleton().logMessage("EGLPBuffer::create used FBConfigID " + StringConverter::toString(glConfigID));
	}
	
	EGLPBuffer::~EGLPBuffer()
	{
		eglDestroySurface(mGlDisplay, mEglDrawable);
		LogManager::getSingleton().logMessage(LML_NORMAL, "EGLPBuffer::PBuffer destroyed");
	}
}
